package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author kabuda
 * @create 2022-09-03 19:44
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String str=split[2]+"已存在";
            return R.error(str);
        }else{
            return R.error("未知错误!");
        }
    }
    @ExceptionHandler(value = CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
            return R.error(ex.getMessage());
    }
}
